package com.ky.pro.java.sharding.ecommerce.aop;

import com.ky.pro.java.sharding.ecommerce.config.DataSourceNames;
import com.ky.pro.java.sharding.ecommerce.config.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.ky.pro.java.sharding.ecommerce.annotation.ReadOnlyDs)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
//        MethodSignature signature = (MethodSignature) point.getSignature();
//        Method method = signature.getMethod();
//        ReadOnlyDs ds = method.getAnnotation(ReadOnlyDs.class);

        DynamicDataSource.setDataSource(DataSourceNames.SLAVE);
        log.info("切换数据源：" + DataSourceNames.SLAVE);

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }

}
